// 请求模块
import axios from 'axios'
import JSONbig from 'json-bigint'
import {Toast} from 'vant'
import router from '@/router/'
const refreshTokenReq=axios.create({
  baseURL:'http://ttapi.research.itcast.cn/'
})
const request=axios.create({
    baseURL:'http://ttapi.research.itcast.cn/',//基础路径
    transformResponse:[function(data){
      try {
        return JSONbig.parse(data)
      } catch (err) {
        return data
      }
    }]
})

import store from '@/store/'

// 请求拦截器
// Add a request interceptor
request.interceptors.request.use(function (config) {
    // Do something before request is sent
    const {user} = store.state
    if(user){
        config.headers.Authorization=`Bearer ${user.token}`
    }
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });
// 响应拦截器
  // Add a response interceptor
axios.interceptors.response.use(function (response) {
  // Any status code that lie within the range of 2xx cause this function to trigger
  // Do something with response data
  return response;
}, function (error) {
  // Any status codes that falls outside the range of 2xx cause this function to trigger
  // Do something with response error
  const status=error.response.status
  if(status===400){
     Toast.fail('客户端请求参数异常')
  }else if(status===401){
    // 如果没有user或者user.token
    const {user}=user.state
    if(!user||user.token){
      // 直接跳转到登录页
      return redirectLogin()
    }
    // 如果有refresh_token,则请求获取新的token
    try {
        const {data}=await refreshTokenReq({
        method:'PUT',
        url:'/app/v1_0/authorizations',
        headers:{
          Authorization:`Bearer${user.refresh_token}`
        }
      })
      user.token=data.data.token
      store.commit('serUser',user)
      return request(error.config)
    } catch (err) {
      
    }
  }else if(status===403){
    Toast.fail('没有权限操作')
  }else if(status>=500){
    Toast.fail('服务端异常，请稍后重试')
  }
  return Promise.reject(error);
});

function redirectLogin(){
   router.replace({
     name:'login',
     query:{
       redirect:router.currentRpute.fullPath
     }
   })
}
// 导出
export default request